<template>
  <div class="forgot-password-container" v-loading="loading" :element-loading-text="loadingText">
    <transition name="fade-slide" mode="out-in">
      <form @submit.prevent="handleResetPassword" class="forgot-form">
        <div class="form-group">
          <label for="forgot-phone">
            <i class="fas fa-mobile-alt"></i> 手机号
          </label>
          <div class="phone-input">
            <input id="forgot-phone" type="tel" v-model="forgotForm.phone" placeholder="请输入注册时的手机号" required
              maxlength="11" @input="formatPhoneNumber">
            <button type="button" class="send-code-btn" :disabled="!canSendCode || isSendingCode"
              @click="sendVerificationCode">
              <span v-if="!isSendingCode">
                {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
              </span>
              <span v-else>
                <i class="fas fa-spinner fa-spin"></i> 发送中...
              </span>
            </button>
          </div>
        </div>

        <div class="form-group">
          <label for="forgot-code">
            <i class="fas fa-sms"></i> 验证码
          </label>
          <div class="input-wrapper">
            <input id="forgot-code" type="text" v-model="forgotForm.verificationCode" placeholder="请输入验证码" required
              maxlength="6">
          </div>
        </div>

        <div class="form-group">
          <label for="forgot-password">
            <i class="fas fa-lock"></i> 新密码
          </label>
          <div class="password-input">
            <input id="forgot-password" :type="showPassword ? 'text' : 'password'" v-model="forgotForm.newPassword"
              placeholder="请输入新密码" required>
            <button type="button" class="toggle-password" @click="showPassword = !showPassword">
              <i :class="showPassword ? 'fas fa-eye-slash' : 'fas fa-eye'"></i>
            </button>
          </div>
          <div class="password-strength" v-if="forgotForm.newPassword">
            <div class="strength-bar" :class="getPasswordStrength(forgotForm.newPassword)"></div>
            <span class="strength-text">{{ getPasswordStrengthText(forgotForm.newPassword) }}</span>
          </div>
        </div>

        <div class="form-group">
          <label for="forgot-confirm-password">
            <i class="fas fa-lock"></i> 确认新密码
          </label>
          <div class="password-input">
            <input id="forgot-confirm-password" :type="showPassword ? 'text' : 'password'"
              v-model="forgotForm.confirmPassword" placeholder="请再次输入新密码" required>
          </div>
          <div v-if="forgotForm.confirmPassword && forgotForm.newPassword !== forgotForm.confirmPassword"
            class="input-message error">
            <i class="fas fa-exclamation-circle"></i> 两次输入的密码不一致
          </div>
        </div>

        <button type="submit" class="submit-btn" :disabled="isResetting || !canResetPassword">
          <span v-if="!isResetting">
            <i class="fas fa-key"></i> 重置密码
          </span>
          <span v-else>
            <i class="fas fa-spinner fa-spin"></i> 重置中...
          </span>
        </button>
      </form>
    </transition>
  </div>
</template>

<script>
import { resetPassword as resetPasswordAPI, sendResetPasswordCode as sendResetPasswordCodeAPI } from "@/api/user";

export default {
  name: 'ForgotPasswordView',
  data() {
    return {
      showPassword: false,
      isResetting: false,
      isSendingCode: false,
      countdown: 0,
      forgotForm: {
        phone: '',
        verificationCode: '',
        newPassword: '',
        confirmPassword: ''
      },
      loading: false,
      loadingText: '重置密码中'
    }
  },
  computed: {
    canSendCode() {
      return /^1[3-9]\d{9}$/.test(this.forgotForm.phone) && this.countdown === 0
    },
    canResetPassword() {
      return (
        this.forgotForm.phone &&
        this.forgotForm.verificationCode &&
        this.forgotForm.newPassword &&
        this.forgotForm.newPassword === this.forgotForm.confirmPassword &&
        this.calculatePasswordStrength(this.forgotForm.newPassword) >= 30 // 确保密码强度至少为中等
      )
    }
  },
  methods: {
    formatPhoneNumber() {
      // 自动格式化手机号为数字
      this.forgotForm.phone = this.forgotForm.phone.replace(/\D/g, '')
    },
    getPasswordStrength(password) {
      const strength = this.calculatePasswordStrength(password)
      if (strength < 30) return 'weak'
      if (strength < 70) return 'medium'
      return 'strong'
    },
    getPasswordStrengthText(password) {
      const strength = this.calculatePasswordStrength(password)
      if (strength < 30) return '弱'
      if (strength < 70) return '中'
      return '强'
    },
    calculatePasswordStrength(password) {
      let strength = 0
      // 长度加分
      strength += Math.min(password.length * 5, 30)
      // 包含大写字母
      if (/[A-Z]/.test(password)) strength += 10
      // 包含小写字母
      if (/[a-z]/.test(password)) strength += 10
      // 包含数字
      if (/\d/.test(password)) strength += 15
      // 包含特殊字符
      if (/[^A-Za-z0-9]/.test(password)) strength += 20
      // 重复字符减分
      if (/(.)\1/.test(password)) strength -= 10
      // 常见模式减分
      if (/123|abc|qwe|asd|zxc/.test(password.toLowerCase())) strength -= 15

      return Math.max(0, Math.min(100, strength))
    },
    async sendVerificationCode() {
      if (!this.canSendCode) return

      this.isSendingCode = true
      setTimeout(async () => {
        this.isSendingCode = false
        this.countdown = 60
        const timer = setInterval(() => {
          this.countdown--
          if (this.countdown <= 0) {
            clearInterval(timer)
          }
        }, 1000)

        try {
          let params = {
            phone: this.forgotForm.phone,
            // type: 'reset' // 指定验证码类型为重置密码
          };

          await sendResetPasswordCodeAPI(params);

          this.$message.success('验证码发送成功');
        } catch (error) {
          this.$message.error(error);
        }
      }, 1000)
    },
    async handleResetPassword() {
      if (!this.canResetPassword) return;

      
      try {
        
        this.isResetting = true;
        this.loading = true;
        // 调用重置密码的API
        let res = await resetPasswordAPI(this.forgotForm);
        if (res != "") {
          
          this.loadingText = '正在跳转到登录页面';

          this.$router.push({ name: 'login' });

          // 清空表单
          this.forgotForm = {
            phone: '',
            verificationCode: '',
            newPassword: '',
            confirmPassword: ''
          };
        } else {
          this.isResetting = false;
          this.loading = false;
        }

      } catch (error) {
        this.isResetting = false;
        this.loading = false;
        this.$message.error(error.message || '密码重置失败，请稍后重试');
      }

    }
  }
}
</script>

<style lang="less" scoped>
@import "@/styles/variables.less";

.forgot-password-container {
  width: 100%;
}

.form-group {
  margin-bottom: 20px;
  position: relative;

  label {
    display: block;
    margin-bottom: 8px;
    font-size: 14px;
    color: @gray-700;
    font-weight: 500;

    i {
      margin-right: 8px;
      color: @gray-500;
    }
  }

  input {
    width: 100%;
    padding: 12px 15px;
    border: 1px solid @gray-300;
    border-radius: 8px;
    font-size: 14px;
    transition: all 0.3s ease;
    background-color: @gray-50;
    height: 46px;
    box-sizing: border-box;

    &:focus {
      outline: none;
      border-color: @primary;
      box-shadow: 0 0 0 3px rgba(@primary, 0.1);
      background-color: white;
    }

    &::placeholder {
      color: @gray-400;
    }
  }

  .phone-input,
  .password-input,
  .input-wrapper {
    position: relative;
    display: flex;
    height: 46px;
    width: 100%;
  }

  .phone-input {
    input {
      flex: 1;
      padding-right: 110px;
    }

    .send-code-btn {
      position: absolute;
      right: 5px;
      top: 50%;
      transform: translateY(-50%);
      height: calc(100% - 10px);
      padding: 0 10px;
      background: @primary;
      color: white;
      border: none;
      border-radius: 6px;
      font-size: 12px;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        background: darken(@primary, 5%);
      }

      &:disabled {
        background: @gray-400;
        cursor: not-allowed;
      }
    }
  }

  .password-input,
  .input-wrapper {
    input {
      flex: 1;
      padding-right: 40px;
    }
  }

  .password-input {
    .toggle-password {
      position: absolute;
      right: 10px;
      top: 50%;
      transform: translateY(-50%);
      height: calc(100% - 20px);
      display: flex;
      align-items: center;
      justify-content: center;
      background: none;
      border: none;
      color: @gray-500;
      cursor: pointer;
      font-size: 16px;

      &:hover {
        color: @primary;
      }
    }
  }

  .input-message {
    margin-top: 6px;
    font-size: 12px;
    display: flex;
    align-items: center;

    i {
      margin-right: 5px;
    }

    &.error {
      color: @danger;
    }

    &:not(.error) {
      color: @success;
    }
  }
}

.password-strength {
  margin-top: 8px;
  display: flex;
  align-items: center;

  .strength-bar {
    height: 4px;
    border-radius: 2px;
    flex-grow: 1;
    margin-right: 10px;
    transition: all 0.3s ease;

    &.weak {
      width: 30%;
      background: @danger;
    }

    &.medium {
      width: 60%;
      background: @warning;
    }

    &.strong {
      width: 100%;
      background: @success;
    }
  }

  .strength-text {
    font-size: 12px;
    color: @gray-600;
  }
}

.submit-btn {
  width: 100%;
  padding: 14px;
  background: @primary;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 20px;

  &:hover {
    background: darken(@primary, 5%);
    transform: translateY(-2px);
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  }

  &:disabled {
    background: @gray-400;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
  }

  i {
    margin-right: 8px;
  }
}

.fade-slide-enter-active,
.fade-slide-leave-active {
  transition: all 0.3s ease;
}

.fade-slide-enter,
.fade-slide-leave-to {
  opacity: 0;
  transform: translateY(10px);
}

@media (max-width: 768px) {
  .form-group {

    .phone-input,
    .password-input,
    .input-wrapper {
      height: 42px;

      input {
        height: 42px;
        padding: 10px 12px;
      }

      .send-code-btn {
        font-size: 11px;
        padding: 0 8px;
      }
    }
  }
}
</style>